package com.dtsz.m2.ui.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.bumptech.glide.Glide;
import com.dtsz.m2.R;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.ui.base.BaseActivity;
import com.dtsz.m2.ui.model.Ecology;
import com.dtsz.m2.ui.model.Users;
import com.dtsz.m2.utils.StringUtils;
import com.dtsz.m2.utils.Utils;
import com.dtsz.m2.utils.widget.FadeTransitionImageView;
import com.dtsz.m2.utils.widget.HorizontalTransitionLayout;
import com.dtsz.m2.utils.widget.PileLayout;
import com.dtsz.m2.utils.widget.VerticalTransitionLayout;
import com.dtsz.m2.volley.VolleyApplication;
import com.dtsz.m2.volley.state.HUCState;

import java.util.ArrayList;
import java.util.List;

public class EcologyActivity extends BaseActivity {
    private static final String TAG = "emmmmmmmmmmm";
    private View positionView;
    private PileLayout pileLayout;
    private List<Ecology> dataList;

    private int lastDisplay = -1;

    private ObjectAnimator transitionAnimator;
    private float transitionValue;
    private HorizontalTransitionLayout countryView, temperatureView;
    private VerticalTransitionLayout addressView, timeView;
    private FadeTransitionImageView bottomView;
    private Animator.AnimatorListener animatorListener;
    private TextView descriptionView;

    private AlertDialog alertDialog1;

    private EditText etUser, etMoney;

    private TextView tvTilte;
    private String tilte;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_ecology);
        super.onCreate(savedInstanceState);
        tvActionbarTitle.setText("生态圈");
        positionView = findViewById(R.id.positionView);
        countryView = findViewById(R.id.countryView);
        temperatureView = findViewById(R.id.temperatureView);
        pileLayout = findViewById(R.id.pileLayout);
        addressView = findViewById(R.id.addressView);
        descriptionView = findViewById(R.id.descriptionView);
        timeView = findViewById(R.id.timeView);
        bottomView = findViewById(R.id.bottomImageView);

        // 1. 状态栏侵入
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        animatorListener = new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                countryView.onAnimationEnd();
                temperatureView.onAnimationEnd();
                addressView.onAnimationEnd();
                bottomView.onAnimationEnd();
                timeView.onAnimationEnd();
            }
            @Override
            public void onAnimationCancel(Animator animation) {

            }
            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        };

        // 3. PileLayout绑定Adapter
        initDataList();
    }

    private void initSecene(int position) {
        countryView.firstInit(dataList.get(position).getCountry());
        tilte = dataList.get(position).getCountry();
        temperatureView.firstInit(dataList.get(position).getTemperature());
        final String state = dataList.get(position).getState();
        final String id = dataList.get(position).getId();
        temperatureView.setOnClickListener(v -> {
            if ("2".equals(state)) {
                String webUrl = dataList.get(position).getWebUrl();
                if (!"0".equals(webUrl)) {
                    if ("任务墙".equals(webUrl)) {
                       String oaid = VolleyApplication.getOaid();
                        String appkey = "85ffd5eb52460ec9de";
                        String uid = "920";//uid
                        String type = "null";//cpl 游戏 gaoe 截图试玩 为null表示全部
                       // new JieTuAd(EcologyActivity.this, null, appkey, uid, type, false, oaid);
                    } else {
                        sendUrl(webUrl);
                    }
                }
            }
        });

        addressView.firstInit(dataList.get(position).getAddress());
        bottomView.firstInit(dataList.get(position).getMapImageUrl());
        timeView.firstInit(dataList.get(position).getTime());
    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
    }

    private void transitionSecene(final int position) {
        if (transitionAnimator != null) {
            transitionAnimator.cancel();
        }
        tilte = dataList.get(position).getCountry();
        countryView.saveNextPosition(position, dataList.get(position).getCountry());
        temperatureView.saveNextPosition(position, dataList.get(position).getTemperature());
        final String state = dataList.get(position).getState();
        final String id = dataList.get(position).getId();
        temperatureView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("2".equals(state)) {
                    String webUrl = dataList.get(position).getWebUrl();
                    if ("任务墙".equals(webUrl)) {
                        String oaid = VolleyApplication.getOaid();
                        String appkey = "85ffd5eb52460ec9de";
                        String uid = "920";//uid
                        String type = "null";//cpl 游戏 gaoe 截图试玩 为null表示全部
                       //new JieTuAd(EcologyActivity.this, null, appkey, uid, type, false, oaid);
                    } else {
                        sendUrl(webUrl);
                    }
                }
            }
        });
        addressView.saveNextPosition(position, dataList.get(position).getAddress());
        bottomView.saveNextPosition(position, dataList.get(position).getMapImageUrl());
        timeView.saveNextPosition(position, dataList.get(position).getTime());
        transitionAnimator = ObjectAnimator.ofFloat(this, "transitionValue", 0.0f, 1.0f);
        transitionAnimator.setDuration(300);
        transitionAnimator.start();
        transitionAnimator.addListener(animatorListener);

    }

    private void isIdentif(final String id) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
//        dialog.setMessage("钱包需要实名认证审核通过，请点击按钮实名认证");
//        dialog.setPositiveButton("实名认证", null);
        View view = LayoutInflater.from(this).inflate(R.layout.item_payment, null);
        dialog.setView(view);
        alertDialog1 = dialog.create();
        alertDialog1.setCancelable(false);
        alertDialog1.show();
        etUser = view.findViewById(R.id.et_user);
        etMoney = view.findViewById(R.id.et_money);
        tvTilte = view.findViewById(R.id.tv_title);
        tvTilte.setText(tilte + "充值");
        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog1.dismiss();
            }
        });
        view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userId = etUser.getText().toString();
                String money = etMoney.getText().toString();
                if (StringUtils.isEmpty(userId)) {
                    showToast("账号不能为空");
                    return;
                }
                if (StringUtils.isEmpty(money)) {
                    showToast("M2币不能为空");
                    return;
                }
                alertDialog1.dismiss();
                Intent intent = new Intent();
                intent.setClass(EcologyActivity.this, GestureLoginActivity.class);
                intent.putExtra("userId", userId);
                intent.putExtra("money", money);
                intent.putExtra("ecologyId", id);
                startActivity(intent);
            }
        });
    }

    /**
     * 调整沉浸状态栏
     */
    private void adjustStatusBarHeight() {
        int statusBarHeight = Utils.getStatusBarHeight(this);
        ViewGroup.LayoutParams lp = positionView.getLayoutParams();
        lp.height = statusBarHeight;
        positionView.setLayoutParams(lp);
    }


    /**
     * 获取网络数据
     */
    private void initDataList() {
        dataList = new ArrayList<>();
        hucRequestInterfase.executeStr(this, Ecology.class,
                HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.ECOLOGY_LIST_URL,
                hucParameInterfase.getRequestParameter(pageVo), false);
//        try {
//            InputStream in = getAssets().open("preset.config");
//            int size = in.available();
//            byte[] buffer = new byte[size];
//            in.read(buffer);
//            String jsonStr = new String(buffer, "UTF-8");
//            JSONObject jsonObject = new JSONObject(jsonStr);
//            JSONArray jsonArray = jsonObject.optJSONArray("result");
//            if (null != jsonArray) {
//                int len = jsonArray.length();
//                for (int j = 0; j < 3; j++) {
//                    for (int i = 0; i < len; i++) {
//                        JSONObject itemJsonObject = jsonArray.getJSONObject(i);
//                        Ecology itemEntity = new ItemEntity(itemJsonObject);
//                        dataList.add(itemEntity);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                if (response instanceof List) {
                    dataList = (List<Ecology>) response;
                    pileLayout.setAdapter(new PileLayout.Adapter() {
                        @Override
                        public int getLayoutId() {
                            return R.layout.item_layout;
                        }

                        @Override
                        public void bindView(View view, int position) {
                            ViewHolder viewHolder = (ViewHolder) view.getTag();
                            if (viewHolder == null) {
                                viewHolder = new ViewHolder();
                                viewHolder.imageView = (ImageView) view.findViewById(R.id.imageView);
                                view.setTag(viewHolder);
                            }

                            Glide.with(EcologyActivity.this).load(dataList.get(position).getCoverImageUrl()).into(viewHolder.imageView);
                        }

                        @Override
                        public int getItemCount() {
                            return dataList.size();
                        }

                        @Override
                        public void displaying(int position) {
                            descriptionView.setText(dataList.get(position).getDescription());
                            if (lastDisplay < 0) {
                                initSecene(position);
                                lastDisplay = 0;
                            } else if (lastDisplay != position) {
                                transitionSecene(position);
                                lastDisplay = position;
                            }
                        }

                        @Override
                        public void onItemClick(View view, int position) {
                            super.onItemClick(view, position);
                        }
                    });
                    //pileLayout.notifyDataSetChanged();
                } else {
                    Toast.makeText(this, response.toString(), Toast.LENGTH_SHORT).show();
                }
                break;
            case HUCState.HUC_REQEUST_CODE_2:
                if (response instanceof Users) {
                    Users user = (Users) response;
                    buCertification = user.getBuCertification();
                    buName = user.getBuName();
                    phone = user.getBuPhone();
                } else {
                    Toast.makeText(this, response.toString(), Toast.LENGTH_SHORT).show();
                }
                break;
        }
        loadDismiss();

    }


    /**
     * 属性动画
     */
    public void setTransitionValue(float transitionValue) {
        this.transitionValue = transitionValue;
        countryView.duringAnimation(transitionValue);
        temperatureView.duringAnimation(transitionValue);
        addressView.duringAnimation(transitionValue);
        bottomView.duringAnimation(transitionValue);
        timeView.duringAnimation(transitionValue);
    }

    public float getTransitionValue() {
        return transitionValue;
    }

    class ViewHolder {
        ImageView imageView;
    }

    //////////////////判断是否实名认证//////////////
    private String biIm;
    private String buCertification;
    private String buName;
    private String phone;
    private AlertDialog cerDialog;

    private void actionId(String id) {
        if ("0".equals(biIm)) {
            Toast.makeText(this, "账号未授权实名认证", Toast.LENGTH_LONG).show();
        } else {
            if (!"1".equals(buCertification)) {
                isIdentifWind();
            } else {//实名认证通
                isIdentif(id);
            }
        }

    }

    private void initData() {
        hucRequestInterfase.executeStr(this, Users.class,
                HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.USERS_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    private void isIdentifWind() {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
        dialog.setMessage("转出需要实名认证审核通过，请点击按钮实名认证");
        dialog.setPositiveButton("实名认证", null);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cerDialog.dismiss();
            }
        });

        cerDialog = dialog.create();
        cerDialog.setCancelable(false);
        cerDialog.show();

        //为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
        cerDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //绑定用户v
                        cerDialog.dismiss();
                        Intent intent = new Intent();
                        intent.setClass(EcologyActivity.this, IdentificationCardActivity.class);
                        intent.putExtra("name", buName);
                        intent.putExtra("card", getSharedPreferences("card"));
                        startActivity(intent);
                    }
                });
    }

}
